package cn.virens.server.tio_tcp.packet;

import java.util.Arrays;

import org.tio.core.intf.Packet;

import cn.virens.common.utils.number.ByteUtil;
import cn.virens.server.common.ReadPacket;

public class TioReadPacket extends Packet implements ReadPacket {
	private static final long serialVersionUID = 7941334824006783017L;
	private static final byte[] EMPTY_BYTES = new byte[0];
	private static final int EMPTY_VALUE = 0;

	private int seq = EMPTY_VALUE;
	private int length = EMPTY_VALUE;
	private int command = EMPTY_VALUE;
	private byte[] data = EMPTY_BYTES;

	@Override
	public int getSeq() {
		return seq;
	}

	public void setSeq(int seq) {
		this.seq = seq % 255;
	}

	@Override
	public int getLength() {
		return length;
	}

	public void setLength(int len) {
		this.length = len;
	}

	@Override
	public int getCommand() {
		return command;
	}

	public void setCommand(int cmd) {
		this.command = cmd;
	}

	@Override
	public byte[] getData() {
		return data;
	}

	public TioReadPacket warp(byte[] data) {
		this.data = data;

		return this;
	}

	@Override
	public byte data(int index) {
		if (data == null) {
			throw new IllegalArgumentException("data is null");
		} else if (index < 0 || index >= data.length) {
			throw new IllegalArgumentException("index is error");
		} else {
			return data[index];
		}
	}

	@Override
	public byte[] data(int start, int length) {
		if (data == null) {
			throw new IllegalArgumentException("data is null");
		} else if (start < 0 || start >= data.length) {
			throw new IllegalArgumentException("start is error");
		} else if (length > data.length) {
			return Arrays.copyOfRange(data, start, data.length);
		} else {
			return Arrays.copyOfRange(data, start, start + length);
		}
	}

	@Override
	public String toString() {
		return "ReadPacket [cmd=" + command + ", data=" + ByteUtil.toHex(data) + "]";
	}

}
